<?php
if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class Mongodbkit
{
    public function __construct() 
    {
        $this->CI =& get_instance();
        $this->CI->config->load('mongodb', FALSE, TRUE);
        $this->config['server']     = $this->CI->config->config['mongodb']['server'];
        $this->config['db']         = $this->CI->config->config['mongodb']['db'];
        $this->config['collection'] = $this->CI->config->config['mongodb']['collection'];

        $this->mongodb    = new MongoClient($this->config['server']);
        $this->collection = $this->mongodb->selectCollection($this->config['db'],$this->config['collection']);
    } 

    public function prototype()
    {
        return $this->mongodb;
    }

    public function find($query = array(),$fields = array(),$limit=false)
    {
        $rs = $this->collection->find($query,$fields);

        if($limit)
        {
            $rs->limit($limit);
        }

        $data = array();

        foreach($rs as $key => $value)
        {
            $data[] = $value;
        }

        return $data;
    }

    public function insert($data,$opt=array())
    {
        try
        {
            $this->collection->insert($data,$opt);
            $id  = $data['_id'];
            $key = '$id';
            return $id->$key;
        }
        catch(Exception $e)
        {
            return false;
        }

    }

    public function save($data,$opt=array())
    {
        try
        {
            $this->collection->save($data,$opt);
            $id  = $data['_id'];
            $key = '$id';
            return $id->$key;
        }
        catch(Exception $e)
        {
            return false;
        }
    }

    public function remove($query,$opt=array())
    {
        try
        {
            $res = $this->collection->remove($query,$opt);
            return $res['n'];
        }
        catch(Exception $e)
        {
            return false;
        }
    }

    public function update($query,$new,$opt=array())
    {
        try
        {
            $res = $this->collection->update($query,$new,$opt);
            return $res['n'];
        }
        catch(Exception $e)
        {
            return false;
        }
    }

}
